package com.dianjing.dianqun.api.dianpai;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dianjing.dianqun.common.ResponseData;
import com.dianjing.dianqun.common.base.BaseRestController;
import com.dianjing.dianqun.model.Content;
import com.dianjing.dianqun.model.CustomerService;
import com.dianjing.dianqun.model.DianPaiCollection;
import com.dianjing.dianqun.model.DianPaiContent;
import com.dianjing.dianqun.model.DianPaiContentComment;
import com.dianjing.dianqun.model.DianPaiContentExt;
import com.dianjing.dianqun.model.DianPaiContentLike;
import com.dianjing.dianqun.model.Site;
import com.dianjing.dianqun.model.User;
import com.dianjing.dianqun.model.UserExt;
import com.dianjing.dianqun.service.ContentService;
import com.dianjing.dianqun.service.SiteService;
import com.dianjing.dianqun.service.UserService;
import com.dianjing.dianqun.service.dianpai.DianPaiCollectionService;
import com.dianjing.dianqun.service.dianpai.DianPaiContentCommentService;
import com.dianjing.dianqun.service.dianpai.DianPaiContentExtService;
import com.dianjing.dianqun.service.dianpai.DianPaiContentLikeService;
import com.dianjing.dianqun.service.dianpai.DianPaiContentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @date : 2017年10月23日
 * 
 * @author: baoyongtao
 * 
 * @see :
 * 
 */
@Api(value = "DianPaiContentController", description = "点拍相关api")
@RestController
@RequestMapping("/api/dianpai")
public class DianPaiContentController extends BaseRestController {
	
	@Autowired
	private CustomerService service;

	@Autowired
	private UserService userService;
	
	@Autowired
	private SiteService siteService;

	@Autowired
	private DianPaiContentService dianPaiContentService;

	@Autowired
	private ContentService contentService;

	@Autowired
	private DianPaiContentCommentService commentService;
	
	@Autowired
	private DianPaiCollectionService  collectionService;
	
	@Autowired
	private DianPaiContentLikeService contentLikeService;
	
	@Autowired
	private DianPaiContentExtService contentExtService;
	
	@ApiOperation(value = "查询点拍详情", notes = "根据点拍的id查询点拍详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "点拍id", dataType = "int", required = true, paramType = "path"),
			@ApiImplicitParam(name = "userId", value = "用户id", dataType = "int", required = true, paramType = "path") })
	@GetMapping("/{id}/{userId}")
	public ResponseData get(@PathVariable(required=true) Integer id, @PathVariable(required=true) Integer userId,HttpServletRequest request) {
		HashMap<String, Object> map = Maps.newHashMap();
		DianPaiContent content = dianPaiContentService.selectByPrimaryKey(id);
		// 处理浏览量
		if (null == content) {
			return new ResponseData(ResponseData.STATUS_ERROR, "文章不存在", id);
		}
		Integer commnetCount = commentService.selectCountByConetnetId(id,userId);
		content.setCommentTotal(commnetCount);
		Integer viewsTotal = content.getViewsTotal() == null ? 1 : content.getViewsTotal() + 1;
		content.setViewsTotal(viewsTotal);
		dianPaiContentService.updateByPrimaryKey(content);
		content.setContentExt(contentExtService.selectByPrimaryKey(content.getContentId()));
		ArrayList<User> userList = new ArrayList<User>();
		// 查询作者
		User user = userService.selectByPrimaryKey(content.getUserId());
		// 是否相互关注
		Boolean bothFolow = userService.isFolow(userId, user.getUserId());
		//=====处理用户的粉丝和文章总数======
		UserExt ext = user.getExt();
		Integer contentCount = contentService.selectCountByUserId(userId);
		Integer fans =  userService.selectFansByUserId(userId);
		if(null==ext) {ext=new UserExt();}
		ext.setContentCount(contentCount);
		ext.setFans(fans);
		userList.add(user);
		//=========================
		map.put("author", userList);
		map.put("isBothFolow", bothFolow);
		//是否点赞
		DianPaiContentLike contentLike = contentLikeService.selectLikeByUser(userId,content.getContentId());
		DianPaiCollection collection = collectionService.selectByPrimaryKey(userId, content.getContentId());
		//组装最近访客
		//开始组装最近访客 自己不可算
		if(userId!=null && !userId.equals(content.getUserId())) {
			Site site = siteService.selectSitelByUserId(content.getUserId());
			if(site!=null) {
				Integer siteId = site.getSiteId();
				boolean isOk = saveSiteFlow(siteId,userId, request);
				if(!isOk) {
					//保存失败 可能要返回信息 目前 不做操作 主要发生在 发开期间
					LOG.error("Save site flow error !!");
				}
			}
		}
		map.put("isLiked", null==contentLike?false:true);
		map.put("isCollection", null==collection?false:true);
		map.put("service", service);
		// 查询最多三条评论 自己可以看到自己 的评论
		List<DianPaiContentComment> list = commentService.select3ByContentId(content,userId);
		content.setCommentList(list);
		map.put("content", content);// 文章
		// 开始组装猜你喜欢 最新更新的文章列表 根据用户id
		List<Content> selectAllContent = contentService.selectContentByLike(userId, 1,10);
		map.put("duessLike", selectAllContent);
		// 开始组装推荐
		List<Content> recommendContent = contentService.selectContentRecommend(userId, 10);
		if(CollectionUtils.isEmpty(recommendContent)) {
			//如果推荐为空  则在查询20条猜你喜欢
			recommendContent=contentService.selectContentByLike(user.getUserId(),2, 10);
		}
		map.put("recommend", recommendContent);
		return new ResponseData(ResponseData.STATUS_OK, "完成", map);
	}

	@ApiOperation(value = "查询点拍列表", notes = "分页查询点拍列表")
	@GetMapping(value = "/list")
	@ApiImplicitParams({ @ApiImplicitParam(dataType = "Integer", name = "userId", value = "用戶Id", paramType = "query"),
			@ApiImplicitParam(dataType = "Integer", name = "pageNum", value = "当前页", paramType = "query") })
	public ResponseData list(@RequestParam(defaultValue = "20") Integer pageSize,@RequestParam Integer userId,
			@RequestParam(defaultValue = "1") Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		List<DianPaiContent> list = dianPaiContentService.selectContentByUserId(userId);
		PageInfo<DianPaiContent> page = new PageInfo<>(list);
		return new ResponseData(ResponseData.STATUS_OK, "查询完成", page);
	}

	@ApiOperation(value = "保存点拍，通过用户id", notes = "保存点拍，通过用户id")
	@PostMapping(value = "/save/{userId}")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "int", name = "userId", required = true, value = "用戶Id", paramType = "path"),
			@ApiImplicitParam(dataType = "string", name = "title", required = true, value = "文章大标题", paramType = "query"),
			@ApiImplicitParam(dataType = "string", name = "txt", required = true, value = "json数据", paramType = "query") })
	public ResponseData save(@PathVariable(required=true) Integer userId, @RequestParam(name = "txt") String txt,
			@RequestParam(name = "title") String title) {
		Date date = new Date();
		DianPaiContent content = new DianPaiContent();
		content.setStatus(DianPaiContent.DIANJING_CHECKED);// 点睛审核状态未审核
		content.setCreateDate(date);// 創建日期
		content.setUserId(userId);// 作者id
		content.setIsTop(false);// 置顶
		content.setTxt(txt);// 存儲的json
		content.setIsRecommend(false);// 推荐
		// 扩展内容
		DianPaiContentExt ext = new DianPaiContentExt();
		ext.setContentId(content.getContentId());
		ext.setOrigin("点群");
		ext.setReleaseDate(date);// 发布日期
		ext.setTitle(title);// 標題
		content.setContentExt(ext);
		try {
			dianPaiContentService.insertContentAndExt(content);
		} catch (Exception e) {
			//数据库不支持emoji表情
			return new ResponseData(ResponseData.STATUS_ERROR, "包含不支持的特殊符号！请检查后重试。", null);
		}
		return new ResponseData(ResponseData.STATUS_OK, "保存完成", "ok");
	}

	
	
	@ApiOperation(value = "收藏/取消点拍文章", notes = "用户收藏点拍文章")
	@GetMapping(value = "/collection/{userId}/{contentId}")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "int", name = "status", required = true, value = "是否收藏(0:是 1：取消)", paramType = "query"),
			@ApiImplicitParam(dataType = "int", name = "userId", required = true, value = "用戶Id", paramType = "path"),
			@ApiImplicitParam(dataType = "int", name = "contentId", required = true, value = "点拍文章Id", paramType = "path")
	})
	public ResponseData collection(@PathVariable(required=true) Integer userId, @RequestParam(required=true) Integer status, 
				@PathVariable(required=true) Integer contentId) {
		DianPaiContent dianPaiContent = dianPaiContentService.selectByPrimaryKey(contentId);
		User user = userService.selectByPrimaryKey(userId);
		if(null==user||dianPaiContent==null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "参数错误", false);
		}
		if(dianPaiContent.getUserId().equals(userId)) {
			//自己不能收藏自己的文章
			return new ResponseData(ResponseData.STATUS_ERROR, "不能自己收藏自己的文章", false);
		}
		DianPaiCollection dianPaiCollection = collectionService.selectByPrimaryKey(userId, contentId);
		Boolean isCollection=null;
		if(status.equals(0)) {
			//收藏点拍
			//查询是否收藏
			if(dianPaiCollection==null) {
				//开始收藏
				DianPaiCollection collection = new DianPaiCollection();
				collection.setInsertDate(new Date());
				collection.setContentId(contentId);
				collection.setUserId(userId);
				collectionService.insertSelective(collection);
			}
			isCollection=true;
		}else if(status.equals(1)){//取消收藏
			if(dianPaiCollection!=null) {
				collectionService.cancelCollection(userId,contentId);
			}
			isCollection=false;
		}
		return new ResponseData(ResponseData.STATUS_OK, (status.equals(0)?"":"取消")+"收藏完成",isCollection);
		
	}
	
	
	@ApiOperation(value = "点赞/取消点拍文章", notes = "用户点赞/取消点拍文章")
	@GetMapping(value = "/likeContent/{userId}/{contentId}")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "int", name = "status", required = true, value = "是/取消 点赞(0:是 1：取消)", paramType = "query"),
			@ApiImplicitParam(dataType = "int", name = "userId", required = true, value = "用戶Id", paramType = "path"),
			@ApiImplicitParam(dataType = "int", name = "contentId", required = true, value = "点拍文章Id", paramType = "path")
	})
	public ResponseData likeContent(@PathVariable(required=true) Integer userId, @RequestParam(required=true) Integer status, 
			@PathVariable(required=true) Integer contentId) {
		DianPaiContent dianPaiContent = dianPaiContentService.selectByPrimaryKey(contentId);
		User user = userService.selectByPrimaryKey(userId);
		if(null==user||dianPaiContent==null) {
			return new ResponseData(ResponseData.STATUS_ERROR, "参数错误", false);
		}
		Boolean isCollection=null;
		//查询赞
		DianPaiContentLike contentLike = contentLikeService.selectLikeByUser(userId, contentId);
		if(status.equals(0)) {
			//开始点赞
			if(contentLike==null) {
				DianPaiContentLike like=new DianPaiContentLike();
				like.setContentId(contentId);
				like.setLikeDate(new Date());
				like.setLikeUserId(userId);
				contentLikeService.insertSelective(like);
			}
			  isCollection=true;
		}else if(status.equals(1)) {
			if(contentLike!=null) {
				contentLikeService.cancelLikeByContentId(userId,contentId);
			}
			isCollection=false;
		}
		
		return new ResponseData(ResponseData.STATUS_OK, (status.equals(0)?"":"取消")+"点赞完成",isCollection);
	}
	 
}
